import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import { userInfoApi } from "../http/api";
import { useUserStore } from "@/store/User";
import LoginVue from "@/views/login/index.vue";
import { ElMessage } from "element-plus";

const routes: RouteRecordRaw[] = [
  {
    path: "/login",
    component: LoginVue,
  },
  {
    path: "/",
    redirect: "/index",
  },
  {
    path: "/",
    component: () => import("../views/home/index.vue"),
    children: [
      { path: "index", component: () => import("../views/index/index.vue") },
    ],
  },
];

const router = createRouter({
  routes,
  history: createWebHashHistory(),
});

router.beforeEach((to, from, next) => {
  const store = useUserStore();
  const token = localStorage.getItem("token");
  if (store.menus.length === 0 && token) {
    userInfoApi().then((res) => {
      if (res.code === 200) {
        store.menus = res.data.menus;
        store.username = res.data.username;
        store.routes.forEach((item1) => {
          const route: RouteRecordRaw = {
            name: item1.name,
            path: `/${item1.name}`,
            component: () => import("../views/home/index.vue"),
            meta: {
              title: item1.title,
            },
            children: item1.children.map((item2) => ({
              name: item2.name,
              path: item2.name,
              component: () =>
                import(`../views/${item1.name}/${item2.name}.vue`),
              meta: {
                title: item2.title,
              },
            })),
          };
          if (item1.children[0].name) {
            route.redirect = "/" + item1.name + "/" + item1.children[0].name;
          }
          router.addRoute(route);
        });
        next(to.fullPath);
      }
    });
  } else if (!token && to.path !== "/login") {
    next("/login");
    ElMessage.error("请先登录");
  } else if (token && store.menus.length !== 0 && to.path === "/login") {
    ElMessage.warning("您已登录");
    next(from.fullPath);
  } else {
    next();
  }
});

export default router;
